<?php

namespace Api\Controller;

use Admin\Model\AdminUserMessage;
use Zend\Authentication\Validator\Authentication;
use Zend\Mvc\Controller\AbstractActionController;
use Zend\Authentication\AuthenticationService;
use Zend\Validator\File\UploadFile;
use Zend\View\Model\ViewModel;
use Admin\Model\AdminUser;
use \Velacolib\Utility\Utility;
use Zend\Form\Form;
use Zend\Form\Element;
use Admin\Model\AdminUserContact;
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
class UserController extends AbstractActionController
{
    protected $topicModel;
    protected $userModel;
    protected $topicImageModel;
    protected $auth;
    protected $userMessage;
    protected $messageTable;
    protected $userContactTable;
    protected $FriendTable;

    public function onDispatch(\Zend\Mvc\MvcEvent $e)
    {
        $this->layout('frontend/layout');

        $this->topicModel = Utility::UserGateway('Admin\Model\AdminTopicTable');
        $this->userModel = Utility::UserGateway('Admin\Model\AdminUserTable');
        $this->topicImageModel = Utility::UserGateway('Admin\Model\AdminTopicImgTable');
        $this->messageTable = UTility::UserGateway('Admin\Model\AdminUserMessageTable');
        //temp delete

        $this->userMessage = Utility::UserGateway('Admin\Model\AdminUserMessageTable');
        $this->userContactTable = Utility::UserGateway('Admin\Model\AdminUserContactTable');
        $this->FriendTable = Utility::UserGateway('Admin\Model\AdminFriendsTable');
        return parent::onDispatch($e);
    }

    public function init()
    {
        //$this->Acl->SetModule('Project');
        //if(!$this->Acl->Check())
        //  $this->redirect()->toRoute('home', array ('action' => 'index'));
    }
    public function indexAction(){

    }

    public function messageAction()
    {
        $this->auth = Utility::CheckLogin($this);
        $message_all = $this->userMessage->fetchAll($this->auth->userid);
        $message_all->setCurrentPageNumber((int)$this->params()->fromQuery('page', 1));
        // set the number of items per page to 10
        $message_all->setItemCountPerPage(ITEM_PER_PAGE);


        $view = new ViewModel(array('message' => $message_all, 'auth' => $this->auth));
        $view->setTerminal(true);
        return $view;
    }

    /*
       public function processregisterAction()
       {


           $response['result'] = false;

           $response['locate'] = '';
           //Ajax function
           if ($this->getRequest()->isPost()) {

               $dataSubmit = $this->params()->fromPost();

               //Check if ajax request is submited
               if (!isset ($dataSubmit['ajax_request']))

                   $this->redirect("/");

               $user_model = new AdminUser();

               $validate = $user_model->validateUserFields($dataSubmit);

               if ($validate['pass']) {

                   $dataSubmit['name'] = $this->params()->fromPost('f_name') . ' ' . $this->params()->fromPost('l_name');

                   $dataSubmit['avatar'] = '';

                   $dataSubmit['status'] = '1';

                   $dataSubmit['user_type'] = '2';

                   $time = time();

                   $dataSubmit['time_reg'] = $time;

                   $dataSubmit['password'] = md5($dataSubmit['email'] . $dataSubmit['password']);

                   unset ($dataSubmit['f_name'], $dataSubmit['l_name'], $dataSubmit['r_password']);

                   $object = Utility::UserGateway('Admin\Model\AdminUserTable')->getUserByEmail($dataSubmit['email']);

                   if (is_object($object)) {

                       $response['result'] = false;

                       $response['message'] = 'This email already exists';

                   } else {

                       $user_model->exchangeArray($dataSubmit);

                       $addUser = Utility::UserGateway('Admin\Model\AdminUserTable')->saveUser($user_model);

                       if ($addUser) {

                           $response['result'] = true;

                           $response['message'] = 'Successfully registration progress';

                           //sending email verify to user register
                           $smtp_option = array(
                               'smtp_user' => 'mrhungmaster1905@gmail.com',
                               'smtp_password' => '`1qa2ws#ED'
                           );
                           $senderInfo = array(
                               'email' => 'mrhungmaster1905@gmail.com',
                               'name' => ' Nguyễn Thanh Hưng'

                           );

                           $RecipientInfo = array(
                               'email' => $dataSubmit['email'],
                               'name' => $dataSubmit['name'],
                               'link' => 'http://' . $_SERVER['HTTP_HOST'] . '/user/verify/' . $time,
                           );

                           $template_path = 'admin/email/tpl/template';

                           $subject = 'Email Verify';

                           Utility::SendMail(true, $smtp_option, $senderInfo, $RecipientInfo, $template_path, $subject);

                       } else $response['message'] = 'Unable to register new user';
                   }


               } else $response['message'] = $validate['message'];
           } else $response['message'] = 'Method not allowed';
           header("ContentType: application/json");
           echo json_encode($response);
           die();
       }
          */

    public function loginAction()
    {
        $response['result'] = false;
        $response['locate'] = '';
        if ($this->getRequest()->isPost()) {
            $data = $this->params()->fromPost();
            $user_table = Utility::UserGateway('Admin\Model\AdminUserTable');
            $user_table->setLoginUser($data);
            $login_obj = new AuthenticationService(null, $user_table);
            $login_obj->authenticate();
            $test = new AuthenticationService();
            if ($test->hasIdentity() == 1) {
                    $response['result'] = true;
                    $response['message'] = 'Login success ....';
                    $response['user_info']  = $this->userModel->getUser($login_obj->getIdentity()->userid);
                    $response['locate'] = 'http://' . $_SERVER['HTTP_HOST'];
             //   }

            } else {
                $response['result'] = false;
                $response['message'] = 'Wrong user or password , Please try again!';
            }
            echo json_encode($response);
            die();
        }

    }

    public function editProfileAction(){
        if($this->getRequest()->isPost()){
            $data = $this->params()->fromPost();
            $user_class = $this->userModel->getUser($data['id']);
            if(isset($data['password']) && $data['password'] != ''){
                $user_class->password = md5($user_class->email.$data['password']);
            }
            if(isset($data['address'])){
                $user_class->address = $data['address'];
            }
            if(isset($data['avatar'])){
                $user_class->avatar = $data['avatar'];
            }
            if(isset($data['phone'])){
                $user_class->phone = $data['phone'];
            }
            if(isset($data['name'])){
                $user_class->name = $data['name'];
            }
            $this->userModel->saveUser($user_class);
            $response['content'] = $user_class;
            $response['message'] = 'Cập nhật thông tin thành công';
            echo json_encode($response);
            die;
        }
        die;
    }

    public function addProfileAction(){
        if($this->getRequest()->isPost()){
            $data = $this->params()->fromPost();
            $user_class = new AdminUser();
            $data['user_type'] = 2;
            $data['password'] = md5($data['email'].$data['password']);
            $user_class->exchangeArray($data);
            $this->userModel->saveUser($user_class);
            echo json_encode($user_class);
            die;
        }
        die;
    }

    public function  CheckUserByEmailAction(){
        $user_email = $this->params()->fromQuery('user_email',0);
        $info = $this->userModel->getUserByEmail($user_email);
        if($info!= null){
            echo 1;
            die;
        }

        echo 0;
        die;
    }
}